<?php
/**
 * Note: 渠道方案
 * Date: 2020/6/07
 */
namespace App\Http\Controllers\Admin;

use App\Models\Game\Center\AppSource;
use App\Models\Game\Center\AppSourceConfig;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class AppSourceConfigController extends CurdController
{
    protected string $classModel = AppSourceConfig::class;

    protected array $searchFields = [
        'id' => self::FIELD_TYPE_NUMERIC,
    ];

    /**
     * @param AppSourceConfig $appSourceConfig
     * @param array $originSources
     */
    protected function syncSources(AppSourceConfig $appSourceConfig, array $originSources = [])
    {
        $sources = $appSourceConfig->sources;
        // TODO 方案数量不会很多, 直接循环所有
        AppSourceConfig::where('id', '<>', $appSourceConfig->id)->get()->map(function(AppSourceConfig $v) use ($sources) {
            $v->sources =  array_diff($v->sources, $sources);
            $v->save();
        });
        // 将当前方案ID同步到对应渠道
        AppSource::whereIn('id', $sources)->get()->each(function (AppSource $source) use ($appSourceConfig) {
            $source->update(['app_source_config_id' => $appSourceConfig->id]);
        });

        // 如果原来有 现在没的渠道
        if ($diffSources = array_diff($originSources, $appSourceConfig->sources)) {
            AppSource::whereIn('id', $diffSources)->get()->each(function(AppSource $source) {
                $source->update(['app_source_config_id' => 0]);
            });
        }
    }

    /**
     * 保存之后校验
     * @param AppSourceConfig $appSourceConfig
     * @param Request $request
     */
    public function storeAfter(AppSourceConfig $appSourceConfig, Request $request)
    {
        $this->syncSources($appSourceConfig);
    }

    /**
     * 更新
     * @param Request $request
     * @param AppSourceConfig $appSourceConfig
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function update(Request $request, $primaryKey)
    {
        $appSourceConfig = $this->model->find($primaryKey);
        $appSourceConfig->fill($request->all());
        $originSources = $appSourceConfig->getOriginal('sources');
        $appSourceConfig->save();
        $this->syncSources($appSourceConfig, $originSources);

        return responseMessage(__('web.success'));
    }

    public function destroyBefore(Model|Collection $model)
    {
        $list = $model instanceof Model ? [$model] : $model;
        foreach ($list as $v) {
            if ($v->sources) {
                AppSource::whereIn('id', $v->sources)->each(function (AppSource $appSource) {
                    $appSource->app_source_config_id = 0;
                    $appSource->save();
                });
            }
        }

    }
}
